import os.path, time, sys, base64, urllib.request
from datetime import datetime
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA


from globally import Run_Dir

# 错误向量表
Error_NoActivationFile = "100"   # 未找到授权文件
Error_DecryptWrong = "101"    # 授权文件解密时出现错误

# 全局变量
activation_file_path = Run_Dir + 'catchdeb.LICENSE'

Rsa_Key = """\
-----BEGIN RSA PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDiAvrUghlwTNHlL3nnc/JAczU8hZq9NF0ZKzg7pZgJi3tkqE+DtbGqJOMLjB6fSSzZjhWEG9xBTt7a5LfHqFcR93/sHmPNCSWrF+wd/c9/1vyFHxHI32WUClMfiUYp1nvACgBpyN5mFkJBfnDQfFSEzmxxYA6IjgQvs/xmDok8tZat1UnaIhnRzDD4aXuQiq2L/BmJ6E80IZF9OMkgWjVXxU1Zw0aWjuM0wIFf59NbkaDiWwbGl5OIPB/l8PX7RvIU2ZrHd5fs9eWgvAq4ojWRiI81kKVcrEP8e3q13YjntU7vyh4+8ZCmdi0xxFQE2WoKRq6+EELPBAejxwW+W4xtAgMBAAECggEBAIrh6eDMUXWAvzpmgjKIPUT9hqk6MGwz0UG2HUgJ6fNzks+33aTB8frrz9k4sViQTs8hUHdt51r6bFd2VLiL6XVQ8XrW8dz80fjhKmcDoI6ePW5QOU2GeZUPAyVN5Z+v/Tt06ewXUxLIes5kNE7pF8bEUj8ZF9Ux78CgiWjtZce3Zke/ajuMEUIhdz1R9GJ4VPNOLwa6qkUoJYphHQBRAOQOtLm/v4f/M12oK5xn4KClE42Meg7ksizWMlFkt3Q67KwdVFspiv+j3ddgfKmNqHDcEsSByk1C12AqRGy7+1akg8urO276+ngEV9o4h7VbxG8iPtSiOM4DvYhVzlh3MsECgYEA/3QcDdWoUNRvNG+72yzUH4zzw/vjKpOkiZdcgsxQgWUEMvwJAxUZquzY2d0DasFKfAQBVByeizYLuYuGSb0/lUJOIEKeo+t758/0t23/uhAno7iufkCmZ8OyCdP1EeQwpSbJ6aNwxXEvmmH9qg6L38Zl11NRYCIbud/HTeOqJEcCgYEA4n6/UwkdQDQQpUacbU3D1NAgBHZCq5hWHDk4EgqD8t+ivPGvUmhYDxvkv2I4vmPt60jwycf8E7PgqnMWTOJ54WfKBriHWAdH94o0IK28GavdLzjPwEnPUKin2RbLOSiKfvb6qwhkW2lboME6s282SdB/nwbcf7YvUxRTyd4dp6sCgYAb/47fmU5UZaQ2nBR75kLtnlZNYbs5PGtpRTS3hUtBk1/NcsBOHS7uA/2Ui1vHhJ30T8ARhv19hpPsZzV1uY9Rfa3wbTzT/IhdFPbeb+j6bLDbie9eGRnj/5fw6dFPf7IxN7ojqG1AxrIP+rOBwwxjn2wkGJavsa1WRweiKtTIGwKBgCunEArZ69hO8JJaHJX4cfDXOASEIm9eCeKgqIzZl/q8XWobDpZMZARtdNXqAVO4gMdjJH1PXOcTOQ7A5aBl2eW2kjpfYD54EMfFzCwsL9+mvxd11JyT3TAHgWoWuY5HoQG9aiyCjo0Lrkw6Uaz5lzX8yEwHD4JRw6c4eLmkZITHAoGAGx1v7/hQcZ8bZqi7p4wQ5nNa10AblORehS2PqO6JwUx59ye9uuipnqUv7xMhm7m/KaqpnGFAAU2cuiusUKaAgrabJ1D9uO+abKKLEhGwuGTwzv9vZWsveA+2xyr7OZp5xQeMZX6DaJlXx54krlpOYgukFLkiU2ScvNqfP4ZcYlc=
-----END RSA PRIVATE KEY-----
"""


class ActivationFile():
    __activationfile__ = activation_file_path  # 激活文件路径
    __rsa_key__ = Rsa_Key
    # name: __read_activationfile__
    # func: 读取激活文件LICENSE里的内容
    # params:
    # return: 激活文件信息info(str)
    # brief: 激活文件位置和脚本运行位置一致: Run_Dir + 'catchdeb.LICENSE'
    @classmethod
    def __read_activationfile__(cls):
        with open(cls.__activationfile__, 'r', encoding='utf-8') as f:
            info = f.read().lstrip().rstrip()
            return info

    # name: __decrypt__
    # func: 解密授权文件，获取时间戳
    # params: text —— 需要解密的文本(str)
    # return: 解密过程正常 —— 解密后的文本cipher_text(str)
    #         解密过程错误 —— Error——DecryptWrong
    # brief： 加密使用RSA加密
    @classmethod
    def __decrypt__(cls, text: str) -> str:
        try:
            cipher_rsa = PKCS1_v1_5.new(RSA.import_key(cls.__rsa_key__))
            bas64_text = base64.b64decode(text)
            cipher_text = cipher_rsa.decrypt(bas64_text,0).decode()
            return cipher_text
        except:
            return Error_DecryptWrong

    # name: get_activationfile_time
    # params:
    # return: 存在激活文件，解密过程正常 —— 解密后文本decrypt_info(str)
    #         存在激活文件，解密过程错误 —— Error_DecryptWrong
    #         不存在激活文件 —— Error_NoActivationFile
    # brief:
    @classmethod
    def get_activationfile_time(cls):
        if os.path.exists(cls.__activationfile__):  # 判断激活文件是否存在
            fileinfo = cls.__read_activationfile__()  # 读取激活文件内容
            decrypt_info = cls.__decrypt__(fileinfo)    # 获取解密结果
            if decrypt_info == Error_DecryptWrong:  # 判断解密过程是否错误
                return Error_DecryptWrong
            else:
                return decrypt_info
        else:
            return Error_NoActivationFile

# name: 检查软件激活状态
# params:
# return:
# brief: 检查系统激活状态，如果激活不正常就退出程序
def check_activation():
    end_time = ActivationFile.get_activationfile_time()
    if end_time == Error_NoActivationFile:
        print("请检查激活文件是否存在。 PATH=",activation_file_path)
        sys.exit()
    if end_time == Error_DecryptWrong:
        print("请检查激活文件是否完整。 PATH=",activation_file_path)
        sys.exit()
    format_pattern = '%Y-%m-%d %H:%M:%S'
    url = 'https://beijing-time.org/'
    response = urllib.request.Request(url=url)
    try:
        request_result = urllib.request.urlopen(response)
        headers = request_result.headers
        net_date = headers.get("date")
        gmt_time = time.strptime(net_date[5:25], "%d %b %Y %H:%M:%S")
        bj_timestamp = int(time.mktime(gmt_time) + 8 * 60 * 60)
        bj_time = datetime.fromtimestamp(bj_timestamp)
        difference = (bj_time - datetime.strptime(end_time, format_pattern))
        if difference.days < 0:
            print('授权检测通过，剩余授权天数: {} 天。授权到期时间： {}'.format(abs(difference.days), end_time))
        else:
            print('软件已过期。请重新获取软件授权。授权到期时间： {}'.format(end_time))
            sys.exit()
    except:
        print('网络异常')
        sys.exit()

def main():
    check_activation()

